package cn.jieruoda.eb.system.service;

import java.util.Date;

import cn.dev33.satoken.util.SaResult;
import cn.jieruoda.eb.system.domain.entity.SystemMenu;
import cn.jieruoda.eb.system.domain.repository.SystemMenuRepository;
import cn.jieruoda.eb.system.dto.MenuDTO;
import cn.jieruoda.eb.system.dto.MenusResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class MenuService implements InitializingBean {

    final SystemMenuRepository systemMenuRepository;

    public MenusResponse initMenus() {
        List<SystemMenu> menus = systemMenuRepository.findByStatusOrderByPidAscSortAsc(1);
        // 构建树形菜单结构
        List<MenuDTO> rootMenus = new ArrayList<>();
        Map<Integer, MenuDTO> menuMap = new HashMap<>();
        for (SystemMenu menu : menus) {
            if ("A".equals(menu.getType())) {
                continue;
            }
            MenuDTO menuDTO = parseMenuDTO(menu);
            menuMap.put(menu.getId(), menuDTO);
            if (menu.getPid() == 0) {
                rootMenus.add(menuDTO);
            } else {
                MenuDTO dto = menuMap.get(menu.getPid());
                if (dto != null) {
                    dto.getChildren().add(menuDTO);
                }
            }
        }
        MenusResponse menusResponse = new MenusResponse();
        menusResponse.setData(rootMenus);
        return menusResponse;
    }

    private static MenuDTO parseMenuDTO(SystemMenu menu) {
        MenuDTO menuDTO = new MenuDTO();
        menuDTO.setId(menu.getId());
        menuDTO.setPid(menu.getPid());
        menuDTO.setName(menu.getName());
        menuDTO.setIcon(menu.getIcon());
        menuDTO.setPerms(menu.getPerms());
        menuDTO.setComponent(menu.getComponent());
        menuDTO.setType(null);
        menuDTO.setSort(menu.getSort());
        menuDTO.setChildren(new ArrayList<>());

        return menuDTO;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
//        Page<SystemMenu> anyOne = systemMenuRepository.findAll(PageRequest.of(0, 1));
//        if (!anyOne.isEmpty()) {
//            return;
//        }
        systemMenuRepository.deleteAll();
        // 商品菜单
        SystemMenu goodsMenu = saveMenu(0, "商品", "Goods", null, "/store", "M", 2);
        saveMenu(goodsMenu.getId(), "商品管理", null, "admin:product:list", "/store/index", "C", 1);
        saveMenu(goodsMenu.getId(), "商品分类", null, "", "/store/sort", "C", 1);
        saveMenu(goodsMenu.getId(), "商品规格", null, "admin:product:rule:list", "/store/attr", "C", 1);
        saveMenu(goodsMenu.getId(), "商品评论", null, "admin:product:reply:list", "/store/comment", "C", 1);

        // 订单菜单
        SystemMenu orderMenu = saveMenu(0, "订单", "Files", null, "/order", "M", 3);
        saveMenu(orderMenu.getId(), "订单", null, "admin:order:list", "/order/index", "C", 1);
        saveMenu(orderMenu.getId(), "订单核销", null, "", "/javaMobile/orderCancellation", "C", 2);
        saveMenu(orderMenu.getId(), "订单统计", null, "", "/javaMobile/orderStatistics", "C", 3);

        // 用户菜单
        SystemMenu userMenu = saveMenu(0, "用户", "User", null, "/user", "M", 4);
        saveMenu(userMenu.getId(), "用户管理 ", null, "admin:user:list", "/user/index", "C", 1);
        saveMenu(userMenu.getId(), "用户标签", null, "admin:user:tag:list", "/user/label", "C", 1);
        saveMenu(userMenu.getId(), "用户等级", null, "admin:system:user:level:list", "/user/grade", "C", 1);
        saveMenu(userMenu.getId(), "用户分组", null, "admin:user:group:list", "/user/group", "C", 1);

        // 内容菜单
        SystemMenu contentMenu = saveMenu(0, "内容", "Management", null, "/content", "M", 5);
        saveMenu(contentMenu.getId(), "文章管理", null, "admin:article:list", "/content/articleManager", "C", 1);
        saveMenu(contentMenu.getId(), "文章分类", null, "", "/content/classifManager", "C", 2);
        saveMenu(contentMenu.getId(), "素材管理", null, "admin:system:attachment:list", "/maintain/picture", "C", 3);

        // 应用菜单
        SystemMenu appMenu = saveMenu(0, "应用", "Promotion", null, "/appSetting", "M", 6);
        SystemMenu publicMenu = saveMenu(appMenu.getId(), "公众号", null, "", "/appSetting/publicAccount", "M", 1);
        SystemMenu replyMenu = saveMenu(publicMenu.getId(), "自动回复", null, "", "/appSetting/publicAccount/wxReply", "M", 1);
        saveMenu(replyMenu.getId(), "微信关注回复", null, "admin:wechat:keywords:reply:info:keywords", "/appSetting/publicAccount/wxReply/follow", "C", 99999);
        saveMenu(replyMenu.getId(), "关键字回复", null, "admin:wechat:keywords:reply:list", "/appSetting/publicAccount/wxReply/keyword", "C", 99999);
        saveMenu(replyMenu.getId(), "无效关键词回复", null, "", "/appSetting/publicAccount/wxReply/replyIndex", "C", 99999);
        saveMenu(publicMenu.getId(), "微信菜单", null, "admin:wechat:menu:public:get", "/appSetting//publicAccount/wxMenus", "C", 0);
        saveMenu(appMenu.getId(), "一号通", null, "admin:pass:is:login", "/operation/onePass", "C", 8);

        // 营销菜单
        SystemMenu marketingMenu = saveMenu(0, "营销", "Histogram", null, "/marketing", "M", 7);
        SystemMenu integralMenu = saveMenu(marketingMenu.getId(), "积分", null, "", "/marketing/integral", "M", 99999);
        saveMenu(integralMenu.getId(), "积分配置", null, "", "/marketing/integral/integralconfig", "C", 99999);
        saveMenu(integralMenu.getId(), "积分日志", null, "admin:user:integral:list", "/marketing/integral/integrallog", "C", 1);

        SystemMenu seckillMenu = saveMenu(marketingMenu.getId(), "秒杀管理", null, "", "/marketing/seckill", "M", 99999);
        saveMenu(seckillMenu.getId(), "秒杀配置", null, "admin:seckill:manger:list", "/marketing/seckill/config", "C", 1);
        saveMenu(seckillMenu.getId(), "秒杀商品", null, "admin:seckill:list", "/marketing/seckill/list", "C", 1);

        SystemMenu bargainMenu = saveMenu(marketingMenu.getId(), "砍价管理", null, "", "/marketing/bargain", "M", 99999);
        saveMenu(bargainMenu.getId(), "砍价商品", null, "admin:bargain:list", "/marketing/bargain/bargainGoods", "C", 1);
        saveMenu(bargainMenu.getId(), "砍价列表", null, "admin:bargain:user:list", "/marketing/bargain/bargainList", "C", 1);

        SystemMenu groupMenu = saveMenu(marketingMenu.getId(), "拼团管理", null, "", "/marketing/groupBuy", "M", 99999);
        saveMenu(groupMenu.getId(), "拼团商品", null, "admin:combination:list", "/marketing/groupBuy/groupGoods", "C", 1);
        saveMenu(groupMenu.getId(), "拼团列表", null, "admin:combination:combine:list", "/marketing/groupBuy/groupList", "C", 1);

        SystemMenu couponMenu = saveMenu(marketingMenu.getId(), "优惠券", null, "", "/marketing/coupon", "M", 1);
        saveMenu(couponMenu.getId(), "优惠券", null, "admin:coupon:list", "/marketing/coupon/list", "C", 1);
        saveMenu(couponMenu.getId(), "领取记录", null, "admin:coupon:user:list", "/marketing/coupon/record", "C", 1);

        // 分销菜单
        SystemMenu distributionMenu = saveMenu(0, "分销", "Connection", null, "/distribution", "M", 8);
        saveMenu(distributionMenu.getId(), "分销配置", null, "admin:retail:spread:manage:get", "/distribution/distributionconfig", "C", 1);
        saveMenu(distributionMenu.getId(), "分销员管理", null, "admin:retail:list", "/distribution/index", "C", 0);

        // 财务菜单
        SystemMenu financeMenu = saveMenu(0, "财务", "Money", null, "/financial", "M", 9);
        SystemMenu commissionMenu = saveMenu(financeMenu.getId(), "财务操作", null, "", "/financial/commission", "M", 99999);
        saveMenu(commissionMenu.getId(), "申请提现", null, "admin:finance:apply:list", "/financial/commission/template", "C", 1);

        SystemMenu recordMenu = saveMenu(financeMenu.getId(), "财务记录", null, "", "/financial/record", "M", 99999);
        saveMenu(recordMenu.getId(), "充值记录", null, "admin:recharge:list", "/financial/record/charge", "C", 1);
        saveMenu(recordMenu.getId(), "资金监控", null, "admin:finance:monitor:list", "/financial/record/monitor", "C", 1);
        saveMenu(financeMenu.getId(), "佣金记录", null, "admin:finance:monitor:brokerage:record", "/financial/brokerage", "C", 1);

        // 设置菜单
        SystemMenu settingMenu = saveMenu(0, "设置", "Tools", null, "/operation", "M", 11);
        saveMenu(settingMenu.getId(), "系统设置", null, "admin:system:config:info", "/operation/setting", "C", 1);

        SystemMenu roleMenu = saveMenu(settingMenu.getId(), "权限管理", null, "", "/operation/roleManager", "M", 2);
        saveMenu(roleMenu.getId(), "管理员列表", null, "admin:system:admin:list", "/admin/list", "C", 1);
        saveMenu(roleMenu.getId(), "角色管理", null, "admin:system:role:list", "/admin/role", "C", 2);
        saveMenu(roleMenu.getId(), "菜单管理", null, "admin:system:menu:list", "/sys/menu", "C", 3);

        SystemMenu deliveryMenu = saveMenu(settingMenu.getId(), "发货设置", null, "", "/operation/deliverGoods", "M", 3);
        SystemMenu takeMenu = saveMenu(deliveryMenu.getId(), "提货设置", null, "", "/operation/deliverGoods/takeGoods", "M", 99999);
        saveMenu(takeMenu.getId(), "核销员", null, "admin:system:staff:list", "/operation/deliverGoods/takeGoods/collateUser", "C", 3);
        saveMenu(takeMenu.getId(), "核销订单", null, "admin:system:order:list", "/operation/deliverGoods/takeGoods/collateOrder", "C", 2);
        saveMenu(takeMenu.getId(), "提货点", null, "admin:system:store:list", "/operation/deliverGoods/takeGoods/deliveryAddress", "C", 1);
        saveMenu(deliveryMenu.getId(), "运费模板", null, "admin:shipping:templates:list", "/operation/deliverGoods/freightSet", "C", 2);
        saveMenu(settingMenu.getId(), "消息通知", "", "admin:system:notification:list", "/operation/notification", "C", 4);

        SystemMenu logisticsMenu = saveMenu(settingMenu.getId(), "物流设置", null, "", "/maintain/logistics", "M", 4);
        saveMenu(logisticsMenu.getId(), "物流公司", null, "admin:express:list", "/maintain/logistics/companyList", "C", 2);
        saveMenu(logisticsMenu.getId(), "城市数据", null, "admin:system:city:list", "/maintain/logistics/cityList", "C", 1);

    }

    private SystemMenu saveMenu(int pid, String name, String icon, String perms, String comp, String typ, int sort) {
        SystemMenu menu = new SystemMenu();
        menu.setPid(pid);
        menu.setName(name);
        menu.setIcon(icon);
        menu.setPerms(perms);
        menu.setComponent(comp);
        menu.setType(typ);
        menu.setSort(sort);
        menu.setStatus(1);
        menu.setCreateTime(new Date());
        menu.setUpdateTime(new Date());
        return systemMenuRepository.save(menu);
    }

    public SaResult createMenu(SystemMenu menu) {
        menu.setPid(menu.getPid() != null ? menu.getPid() : 0); // 确保 pid 有默认值
        menu.setCreateTime(new Date());
        menu.setUpdateTime(new Date());
        menu.setStatus(1);
        systemMenuRepository.save(menu);
        return SaResult.ok("创建成功");
    }

    public SaResult updateMenu(SystemMenu menu) {
        SystemMenu existingMenu = systemMenuRepository.findById(menu.getId())
                .orElseThrow(() -> new RuntimeException("菜单不存在"));

        menu.setCreateTime(existingMenu.getCreateTime());
        menu.setUpdateTime(new Date());
        menu.setStatus(existingMenu.getStatus());
        systemMenuRepository.save(menu);
        return SaResult.ok("更新成功");
    }

    public SaResult deleteMenu(Integer id) {
        // 检查是否有子菜单
        List<SystemMenu> children = systemMenuRepository.findByPid(id);
        if (!children.isEmpty()) {
            return SaResult.error("请先删除子菜单");
        }
        systemMenuRepository.deleteById(id);
        return SaResult.ok("删除成功");
    }

    public SaResult moveMenu(Integer id, Integer pid, Integer sort) {
        SystemMenu menu = systemMenuRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("菜单不存在"));

        menu.setPid(pid);
        menu.setSort(sort);
        menu.setUpdateTime(new Date());
        systemMenuRepository.save(menu);
        return SaResult.ok("移动成功");
    }
}
